package com.wy.thread_safe.locks_demo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 美女
 * @date 2022/04/25 17:08
 *
 **/
public class Main5 {
    private static final Lock lock=new ReentrantLock();
    static class MyThread extends Thread{
        @Override
        public void run() {
            boolean b= false;
            try {
                b = lock.tryLock(5, TimeUnit.SECONDS);//等五秒钟
                if(b==true){
                    //加锁成功了
                    System.out.println("加锁成功");
                    System.out.println("子线程进入临界区");
                }else {
                    System.out.println("5s之后加锁失败");
                }
            } catch (InterruptedException e) {
                System.out.println("被人打断了");
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        lock.lock();//主线程已锁上
        MyThread t=new MyThread();
        t.start();
        TimeUnit.SECONDS.sleep(10);
//        t.interrupt();
        lock.unlock();
        t.join();
    }
}
//lock.tryLock(5, TimeUnit.SECONDS);//等五秒钟
//结果：被人打断了